package com.fin.zw.intelligentbot.util;


import com.fin.zw.intelligentbot.model.verbal.NodeInfo;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

public class JsonToTree {

    /**
     * 转数据集合类型
     *
     * @param list
     * @return
     */
    public static Map<String, NodeInfo> getMapNodeInfo(List<NodeInfo> list) {
        Map<String, NodeInfo> map = new HashMap<>();
        for (NodeInfo nodeInfo : list) {
            map.put(nodeInfo.getId(), nodeInfo);
        }
        return map;
    }

    /**
     * 组装话术数据
     *
     * @param list
     * @param info（根节点）
     * @return
     */
    public static NodeInfo getParentNodeInfo(List<NodeInfo> list, NodeInfo info) {
        List<NodeInfo> leafs = getLeafNodeInfo(list);
        list.removeAll(leafs);//去掉叶子节点的数据集合
        if (list != null && list.size() > 0) {
            Map<String, NodeInfo> map = getMapNodeInfo(list);
            for (NodeInfo node : leafs) {
                if (map.containsKey(node.getPid())) {
                    NodeInfo nodeInfo = map.get(node.getPid());
                    System.out.println("id是：" + node.getId() + ",父id是：" + node.getPid());
                    if (node.getFlowSign().equals("right")) {
                        System.out.println("id是：" + node.getId() + ",右节点");
                        nodeInfo.setRight(node);
                    } else if (node.getFlowSign().equals("left")) {
                        System.out.println("id是：" + node.getId() + ",左节点");
                        nodeInfo.setLeft(node);
                    } else if (node.getFlowSign().equals("next")) {
                        System.out.println("id是：" + node.getId() + ",中间节点");
                        nodeInfo.setNext(node);
                    }
                }
            }
            getParentNodeInfo(list,info);
        }
        return info;
    }


    /**
     * 找到所有的叶子节点
     *
     * @param list
     * @return
     */
    public static List<NodeInfo> getLeafNodeInfo(List<NodeInfo> list) {
        List<NodeInfo> leafList = new ArrayList<>();
        Map<String, List<NodeInfo>> collect = list.stream().collect(Collectors.groupingBy(NodeInfo::getPid));
        for (NodeInfo nodeInfo : list) {
            if (!collect.containsKey(nodeInfo.getId())) {
                leafList.add(nodeInfo);
            }
        }
        return leafList;
    }
}
